package com.mxchip.livestarmobile.mobile

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.Navigation
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.NavigationUI
import com.mxchip.livestarmobile.R
import com.mxchip.livestarmobile.mobile.constant.RxConstant
import com.mxchip.livestarmobile.mobile.repository.RoomClientRepository
import com.mxchip.livestarmobile.mobile.state.SystemData
import com.mxchip.livestarmobile.mobile.util.RingtoneManagement.LocalRingManagement
import com.mxchip.livestarmobile.mobile.util.RxBus.RxBus
import com.mxchip.livestarmobile.mobile.util.RxBus.RxSchedulersHelper
import com.mxchip.livestarmobile.mobile.util.Utils
import com.umeng.analytics.MobclickAgent
import com.videohigh.hxb.roomclient.event.InvitationEvent
import com.mxchip.livestarmobile.mobile.update.UpdateInstance
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_main.*
import java.util.concurrent.TimeUnit

class MainActivity : AppCompatActivity() {

    private lateinit var invitationEventObservable: Observable<InvitationEvent>
    private lateinit var invitationEvent: InvitationEvent
    private val updateInstance by lazy {
        UpdateInstance.getInstance(this)
    }
    private val disposable: Disposable by lazy {
        Observable.interval(0, 60 * 15.toLong(), TimeUnit.SECONDS)
                .compose(RxSchedulersHelper.io())
                .filter {
                    Utils.getTopActivity(applicationContext).contains("MainActivity")
                }
                .subscribe {
                    upgradeCheck()
                }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Log.d(TAG, "onCreate: SystemData.userId:${SystemData.userId()} SystemData.deviceId:${SystemData.deviceId()} SystemData.roomId:${SystemData.roomId()}")
        RoomClientRepository.init(SystemData.userId(), SystemData.deviceId(), SystemData.roomId(), SystemData.clientType)
        RoomClientRepository.connect()


        val appBarConfiguration = AppBarConfiguration.Builder(
                R.id.navigation_meeting, R.id.navigation_recent, R.id.navigation_contact, R.id.navigation_mine)
                .build()
        val navController = Navigation.findNavController(this, R.id.nav_host_fragment)
        // NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        nav_view.setOnNavigationItemReselectedListener { menuItem: MenuItem? -> }
        NavigationUI.setupWithNavController(nav_view, navController)

        val dialog = AlertDialog.Builder(this).setTitle(getString(R.string.tips)).setMessage(getString(R.string.check_net)).setPositiveButton(getString(R.string.sure_str)) { dialog, which ->
            RoomClientRepository.disconnect()
            RoomClientRepository.connect()
        }.setCancelable(false).create()

//        lifecycleScope.launch {
//            delay(5 * 1000)

        RoomClientRepository.isConnect.observe(this@MainActivity, androidx.lifecycle.Observer {

            if (!it && !dialog.isShowing) {
                dialog.show()
            }
            if (it && dialog.isShowing) {
                dialog.dismiss()
            }
            if (it){
                updateInstance.autoCheck(this)
            }
        })
//        }

        /*Observable.interval(5, 5, TimeUnit.SECONDS)
                .compose(provider.bindToLifecycle())
                .compose(RxSchedulersHelper.io_main())
                .subscribe {
                    if (SystemData.getInstance().currentState == State.OFFLINE && !dialog.isShowing) {
                        dialog.show()
                    }
                    if (SystemData.getInstance().currentState == State.IDLE && dialog.isShowing) {
                        dialog.dismiss()
                    }
                }*/

    }

    @SuppressLint("CheckResult")
    private fun initRxBus() {
        invitationEventObservable = RxBus.get().register(RxConstant.INVITATION_EVENT, InvitationEvent::class.java)
        invitationEventObservable.compose(RxSchedulersHelper.io_main()).subscribe({ event ->
            invitationEvent = event
            jumpToAnswerActivity(event)
        }) { error -> Log.e(TAG, "initRxBus jumpToCallActivity $error") }
    }

    override fun onDestroy() {
        super.onDestroy()

        LocalRingManagement.getInstance().release()
    }

    override fun onResume() {
        super.onResume()
        MobclickAgent.onResume(this) // 不能遗漏
        initRxBus()
    }

    override fun onPause() {
        super.onPause()
        MobclickAgent.onPause(this) // 不能遗漏
        RxBus.get().unregister(RxConstant.INVITATION_EVENT, invitationEventObservable)
    }
    /**
     * 跳转到等待接听界面
     *
     * @param inviteNotifyBean server data
     */
    private fun jumpToAnswerActivity(invitationEvent: InvitationEvent) {
        CallActivityA.open(this, invitationEvent)
    }

    private fun upgradeCheck() {
        updateInstance.autoCheck(this)
    }

    companion object {
        private const val TAG = "MainActivity"
    }
}